package com.mall.seckill_mall.exception.handler;

import com.mall.seckill_mall.common.Result;
import com.mall.seckill_mall.enums.CodeMessage;
import com.mall.seckill_mall.exception.GoodsException;
import com.mall.seckill_mall.exception.OrderException;
import com.mall.seckill_mall.exception.SeckillException;
import com.mall.seckill_mall.exception.UserException;
import com.mall.seckill_mall.utils.ResultUtil;
import io.lettuce.core.RedisCommandTimeoutException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(UserException.class)
    public Result handleUserException(UserException e) {
        return ResultUtil.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(OrderException.class)
    public Result handleOrderException(OrderException e) {
        return ResultUtil.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(GoodsException.class)
    public Result handleGoodsException(GoodsException e) {
        return ResultUtil.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(SeckillException.class)
    public Result handleSeckillException(SeckillException e) {
        return ResultUtil.error(e.getCode(), e.getMessage());
    }
    @ExceptionHandler(BindException.class)
    public Result handleSalerException(BindException e) {
        List<FieldError> errors = e.getFieldErrors();
        FieldError error = errors.get(0);
        CodeMessage codeMsg = CodeMessage.BIND_ERROR;
        String message = codeMsg.getMessage() + ": " + error.getDefaultMessage();
        return ResultUtil.error(codeMsg.getCode(), message);
    }

    @ExceptionHandler(RedisCommandTimeoutException.class)
    public Result handlerRedisConException(RedisCommandTimeoutException e) {
        return ResultUtil.error(CodeMessage.REDIS_CON_ERROR);
    }

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        e.printStackTrace();
        CodeMessage codeMessage = CodeMessage.SERVER_ERROR;
        String message = codeMessage.getMessage().concat(e.getMessage());
        return ResultUtil.error(codeMessage.getCode(), message);
    }
}
